<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>发送AJAX请求</button>
    <script>
      function sendAJAX(method, url) {
        return new Promise((resolve, reject) => {
          let xhr = new XMLHttpRequest();
          xhr.responseType = "json";
          xhr.open(method, url);
          xhr.send();
          xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
              //判断
              if (xhr.status >= 200 && xhr.status < 300) {
                //成功
                resolve({
                  status: xhr.status, //状态码
                  statusText: xhr.statusText, //状态字符串
                  headers: xhr.getAllResponseHeaders(),  //响应头
                  data: xhr.response,    //响应体
                  request: xhr
                });
              } else {
                //失败
                reject(xhr.status);
              }
            }
          };
        });
      }

      //获取按钮
      let btn = document.querySelector("button");

      btn.onclick = async function () {
        try {
          //获取成功的结果值 响应体
          let response = await sendAJAX("get", "http://api.xiaohigh.com/goods");
          console.log(response);
        } catch (e) { //抓紧
          console.warn(e);
        }
      };
    </script>
  </body>
</html>
